import Vue from 'vue';
import md5 from "@/util/md5/md5.js";
import $config from './config';
import $store from '@/store/index';

var headerData = {
	'Content-Type': 'application/json;charset=utf-8',
	'Accept': 'application/json'
};

var common = {
	app_secret: 'hGAHbEwaEan6pMNb',
	app_key: 'acg53534896',
	version: '1.0'
}

// md5加密
function requestEncrypt(data) {
	let secret = common.app_secret;
	let _str = '';
	let sorted = {},
		keys = Object.keys(data);
	keys.sort();
	keys.forEach((key) => {
		_str += key + data[key];
	});
	_str = secret + _str + secret;
	return md5.hex_md5_32Upper(_str);
}

function requestApi(type, url, data = {}) {
	let locToken = uni.getStorageSync('token')
	let token = $store.state.token !== '' ? $store.state.token : locToken;
	if (typeof(data.loginType) != 'undefined' && data.loginType == 1) {
		//存在登录标识，且为需要登录，则校检token信息
		if (token == '' || token == undefined) {
			uni.clearStorage();
			uni.navigateTo({
				url: '/pages/login/index',
			});
			return false;
		}
	}
	let showLoading = ((typeof data.showLoading == 'undefined' || data.showLoading) ? true : false);
	data.app_key = common.app_key;
	data.version = common.version;
	data.timestamp = (new Date()).valueOf();
	delete data.sign; //true
	delete data.loginType;
	delete data.showLoading;
	data.sign = requestEncrypt(data);
	headerData.Authorization = 'Bearer ' + token;
	url = $config.baseUrl + url;
	return new Promise((resolve, reject) => {
		if (showLoading) {
			uni.showLoading({
				title: '加载中'
			});
		}
		uni.request({
			url: url,
			method: type,
			header: headerData,
			data: data,
			success: (res) => {
				if (res.statusCode == 401) {
					//用户登录过期，需重新登录，先清除本地存储，跳转登录页面
					uni.clearStorage();
					uni.navigateTo({
						url: '/pages/login/index',
					});
					return false;
				}
				resolve(res.data);
			},
			fail: (err) => {
				reject(err);
			},
			complete: () => {
				if (showLoading) {
					uni.hideLoading();
				}
			}
		});
	})
}

function uploadApi(type, url, options = {}) {
	let locToken = uni.getStorageSync('token')
	let token = $store.state.token !== '' ? $store.state.token : locToken;
	if (typeof(options.formData) != 'undefined' && typeof(options.formData.loginType) != 'undefined' && options.formData
		.loginType == 1) {
		//存在登录标识，且为需要登录，则校检token信息
		if (token == '' || token == undefined) {
			uni.clearStorage();
			uni.navigateTo({
				url: '/pages/login/index',
			});
			return false;
		}
	}
	options.url = $config.baseUrl + url
	options.header = options.header || {}
	options.header.Authorization = 'Bearer ' + token
	//进行数据加密处理
	options.formData = options.formData || {};
	options.formData.app_key = common.app_key;
	options.formData.timestamp = (new Date()).valueOf();
	options.formData.version = common.version;
	delete options.formData.sign; //true
	delete options.formData.loginType; //true
	options.formData.sign = requestEncrypt(options.formData);

	return new Promise((res, rej) => {
		uni.showLoading({
			title: '请求中'
		});
		uni.uploadFile({
			...options,
			success: (uploadFileRes) => {
				if (uploadFileRes.statusCode !== 200) {
					return uni.showToast({
						title: '上传图片失败',
						icon: 'none'
					});
				}
				let data = JSON.parse(uploadFileRes.data)
				res(data)
			},
			fail: (err) => {
				rej(err)
			},
			complete: () => {
				uni.hideLoading();
			}
		});
	});
}


export default {
	requestApi,
	uploadApi
}